package com.ejlchina.tool.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentCheckIndexFixBinding
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.extension.safeNavigate
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.launch

class CheckIndexFixFragment: BaseBindingFragment2<FragmentCheckIndexFixBinding>() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setHeadVisibility(View.GONE)
        initListeners()
        checkIsAllConnectIndexFix()
    }
    private fun checkIsAllConnectIndexFix(){
        if (viewModelActivity.getAllConnectDevicesCount() == 0) return
        val isAllDeviceIndexFix = GlobalConnectObject.getCurrentConnectDeviceList().all { it.bucketNo > 0 }
        if (isAllDeviceIndexFix){
            findNavController().safeNavigate(R.id.action_check_index_fix_to_config_fragment)
        }
    }

    private fun initListeners(){
        binding.includeNoIndexFix.btnIndexFix.setOnClickListener {
            findNavController().safeNavigate(R.id.action_check_index_fix_to_index_fix_fragment)
        }

        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                setConnectCount()
            }
        }

        binding.includeHead.tvConnectCount.setOnClickListener {
            findNavController().safeNavigate(R.id.action_check_index_fix_to_scan)
        }

        binding.includeHead.ivMenu.setOnClickListener {
            (requireActivity() as MainActivity).openDraw()
        }
    }

    override fun whenDeviceDisConnect(disConnectDevice: BleDevice) {
        super.whenDeviceDisConnect(disConnectDevice)
        setConnectCount()
        checkIsAllConnectIndexFix()
    }

    private fun setConnectCount(){
        if (isAdded){
            binding.includeHead.tvConnectCount.text = "${viewModelActivity.getAllConnectDevicesCount()}"
        }
    }

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentCheckIndexFixBinding {
        return FragmentCheckIndexFixBinding.inflate(inflater,container,true)
    }

    override fun initOnCreateView() {
        super.initOnCreateView()
        setActionBarPadding(false)
    }
}